// 物业通知
import React,{useState} from 'react';
import { makeStyles, useTheme, withStyles } from '@material-ui/core/styles';
import TableRow from '@material-ui/core/TableRow';
import TableCell from '@material-ui/core/TableCell';
import MessagePage from './MessagePage'

import NewMessageDialog from './NewMessageDialog'
import MessageDoWork from './MessageDoWork'
import SelectPeople from './SelectPeople'
import fetch from '../../../assets/utils/fetch'

// 表格标题样式
const StyledTableCell = withStyles(theme => ({
    head: {
        // backgroundColor: '#47484c',
        color: '#333',
        fontWeight: 'bold'
    }
}))(TableCell);


/**
 * 创建一行数据
 * @param {object} feedBack 意见反馈
 * @param {number} type 类型 
 * @param {React.Component} doSomething 组件（操作） 
 */
function createData(message) {
    return {
        ...message
    };
}

// let message = {
//     title: '消防安全告知书',//头像
//     content: '本月15日方家花苑20栋一单元1802', //内容
//     sendPeoples: 266, //发送人数
//     updateDate: '2019-03-03 12:00:00',   //更新日期
// }
// let message2 = {
//     title: '幸打造福小区',//头像
//     content: '文明从自我做起，让自己去影响他人', //内容
//     sendPeoples: 266, //发送人数
//     updateDate: '2019-03-03 12:00:00',   //更新日期
// }
// // table数据
// const rows = [
//     createData(message),
//     createData(message),
//     createData(message2),
//     createData(message),
//     createData(message2),
//     createData(message),
// ];

// 表格标题
function TableHeadRow(){
    return (
        <TableRow>
            <StyledTableCell>通知名称</StyledTableCell>
            <StyledTableCell>通知内容</StyledTableCell>
            <StyledTableCell>发送人数</StyledTableCell>
            <StyledTableCell>更新时间</StyledTableCell>
            <StyledTableCell>操作</StyledTableCell>
        </TableRow>
    )
}
function TableBodyRow(props){
    // console.log(props)
    const row = props.row;
    return (
        <TableRow >
            <TableCell 
                component="th" 
                scope="row"
                style={{
                    maxWidth:'180px',
                    overflow: 'hidden',
                    textOverflow:'ellipsis',
                    whiteSpace: 'nowrap'
                }}
            >
                {row.title}
            </TableCell>
            <TableCell 
                style={{
                    maxWidth:'350px',
                    overflow: 'hidden',
                    textOverflow:'ellipsis',
                    whiteSpace: 'nowrap'
                }}
            >
            {row.content}
            </TableCell>
            <TableCell>{row.sendPeoples || 400}</TableCell>
            <TableCell>{row.modified}</TableCell>
            <TableCell>
                <MessageDoWork 
                    row={row} 
                    openNewMessageDialog={props.openNewMessageDialog}
                    openSendDialog={props.openSendDialog}
                />
            </TableCell>
        </TableRow>
    )
}

export default function App(props){
    const [dialogBaseText, setDialogBaseText] = useState({
        dialogTitle:'',
        titleName:'通知标题',
        titlePlaceholder:'给通知起个标题吧',
        linkPlaceholder:'链接地址',
        littleContentPlaceholder:'简介内容最多不超过21个字符，（最多10个汉字）',
        contentPlaceholder:'通知内容最多不超过140个字符',
    });
    
    // 列表
    const [rows, setrows] = useState([]);
    // 共几条数据
    const [rowsCount, setrowsCount] = useState(0);
    
    const newAdata = {
        title:'',
        pic:'',
        link:'',
        smallContent:'',
        content:'',
        type:1, //物业
    }

    const [aData, setAData] = useState({...newAdata});
    
    // 打开dialog action = 新建 | 编辑 ，如果是编辑obj是编辑的那条数据
    function openNewMessageDialog(action,obj){
        // 更新弹框标题
        setDialogBaseText({...dialogBaseText,dialogTitle:`${action}通知`});
        if(action == '新建'){
            setAData({...newAdata})
        }
        else{
            setAData(obj)
        }
        // 显示弹框
        props.setNewMessageShow(true);
        console.log(obj);
    }
    // 新建 | 编辑 窗口中值的变化
    function handleValueChange(key,value){
        // console.log(key,value);
        setAData({
            ...aData,
            [key]:value
        })
    }
    // 关闭dialog
    function closeNewMessageDialog(){
        props.setNewMessageShow(false);
    }
    // 保存信息
    function saveMessage(){
        console.log('保存',aData)
        let params = {
            agent_id: 1,
            pic: aData.pic,
            url: aData.link,
            first_title: aData.title,
            second_title: aData.smallContent,
            content: aData.content
        }
        // 如果是新增 才传announce_classify_id
        if (aData.type) {
            params.announce_classify_id = aData.type
        }
        // 如果是编辑 才传id
        if (aData.id != undefined) {
            params.id = aData.id;
        }

        fetch.post('/self/server/announce/addAnnounce', params, (err, res) => {
            if (err) {
                props.setmessage({
                    ...props.message,
                    type:props.error,
                    text:err.toString(),
                    open:true
                })
            }
            else {
                if (res.code == 1) {
                    props.setmessage({
                        ...props.message,
                        type:props.success,
                        text:res.alertMsg,
                        open:true
                    })
                    closeNewMessageDialog();
                    fetchRows(1)
                }
                else {
                    props.setmessage({
                        ...props.message,
                        type:props.warning,
                        text:res.alertMsg,
                        open:true
                    })
                }
            }
        })
    }
    // 取消保存
    function cancelMessage(){
        console.log('取消')
        closeNewMessageDialog()
    }
    // 打开选择人弹窗
    function openSendDialog(obj){
        console.log(obj)
        setAData(obj);
        props.setSelectPeopleShow(true);
    }
    // 关闭
    function closeSendDialog(){
        props.setSelectPeopleShow(false);
    }
    // 取消选择人弹窗
    function cancelSendDialog(){
        closeSendDialog();
    }

    function fetchRows(page,limit,callback){
        fetch.getJson(`/self/server/announce/getProperty?agent_id=1&page=${page || 1}&limit=${limit || 5}`,(err,res) =>{
            if(err){
                props.setmessage({
                    ...props.message,
                    type:props.error,
                    text:err.toString(),
                    open:true
                })
            }
            else{
                if(res.code == 1){
                    let newRows = res.data.announce.items;
                    // 返回的数据是数组格式才更新数据
                    if(newRows instanceof Array){
                        // 如果列表里有数据，则以新曾
                        let _newRows = [];
                        // 处理数据，将从后台获取的数据转换在本地写好的数据格式
                        newRows.forEach((item) =>{
                            let row = {
                                id:item.id,
                                title:item.first_title,
                                smallContent:item.second_title,
                                pic:item.pic || '',
                                link:item.url || '',
                                content:item.content,
                                modified:item.modified,
                                created:item.created,
                                status:item.status
                            }
                            _newRows.push(row);
                        })
                        setrows(_newRows)
                        setrowsCount(res.data.announce.total_items)
                        callback && callback();
                    }
                    else{
                        props.setmessage({
                            ...props.message,
                            type:props.error,
                            text:'res.data.announce.items 不是个数组',
                            open:true
                        })
                    }
                }
                else{
                    props.setmessage({
                        ...props.message,
                        type:props.warning,
                        text:err.toString(),
                        open:true
                    })
                }
            }
        })
    }
    // 发送
    function handleSend(){
        // /self/server/announce/sendAnnounce
        fetch.post('/self/server/announce/sendAnnounce', {id:aData.id}, (err, res) => {
            if (err) {
                props.setmessage({
                    ...props.message,
                    type:props.error,
                    text:err.toString(),
                    open:true
                })
            }
            else {
                if (res.code == 1) {
                    props.setmessage({
                        ...props.message,
                        type:props.success,
                        text:res.alertMsg,
                        open:true
                    })
                    cancelSendDialog();
                    fetchRows(1)
                }
                else {
                    props.setmessage({
                        ...props.message,
                        type:props.warning,
                        text:res.alertMsg,
                        open:true
                    })
                }
            }
        })
    }
    // 列表分页发生变化
    function handleChangePage(newPage,callback){
        console.log(newPage)
        fetchRows(newPage,5,callback);
    }

    React.useEffect(() =>{
        fetchRows(1);
    },[])

    return (
        <React.Fragment>
            <MessagePage
                rows={rows}
                rowsCount={rowsCount}
                TableHeadRow={TableHeadRow}
                TableBodyRow={TableBodyRow}
                handleChangePage={handleChangePage}
                openNewMessageDialog={openNewMessageDialog}
                openSendDialog={openSendDialog}
                searchInputPlaceholder="请输入通知名称"
            />
            <NewMessageDialog
                baseText={dialogBaseText}
                show={props.newMessageShow}
                save={saveMessage}
                cancel={cancelMessage}
                onClose={closeNewMessageDialog}
                dialogData={aData}
                handleValueChange={handleValueChange}
            />
            <SelectPeople 
                show={props.selectPeopleShow}
                cancel={cancelSendDialog}
                handleSend={handleSend}
            />
        </React.Fragment>
    )
}